package com.clip.service;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clip.dao.UserDAO;
import com.clip.dao.UserEmailDAO;
import com.clip.dao.UserEmailEventDAO;
import com.clip.entity.User;
import com.clip.entity.UserEmail;
import com.clip.entity.UserEmailEvent;
import com.clip.util.ToolsUtils;
import com.clip.util.mail.SimpleMailSender;

@Service
@Transactional
public class UserEmailService {
	@Autowired
	private UserEmailDAO userEmailDAO;
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private UserEmailEventDAO userEmailEventDAO;
	
	public UserEmail getUserEmailByEmail(String email){
		UserEmail userEmail=null;
		List<UserEmail> list = userEmailDAO.findByEmail(email);
		if(list!=null&&list.size()>0){
			userEmail=list.get(0);
		}
		return userEmail;
	}
	public void updateUserEmail(UserEmail instance){
		userEmailDAO.attachDirty(instance);
	}
	public UserEmail addUserEmail(UserEmail instance){
		userEmailDAO.save(instance);
		return getUserEmailByEmail(instance.getEmail());
	}
	public void deleteEmail(String email,User user){
		UserEmail userEmail = getUserEmailByEmail(email);
		if(userEmail!=null){
			String hql = "UPDATE UserEmailEvent uel SET uel.status=1 WHERE uel.uid="+user.getId()+" AND uel.type=2 AND uel.obj='"+userEmail.getEmail()+"'";
			userEmailEventDAO.executeQuery(hql);
			userEmailDAO.delete(getUserEmailByEmail(email));
		}
	}
	public String activite(String activate){
		String result="此链接无效";
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(activate, 2,false);
		if(uel!=null){
			uel.setClick(1);
			User user = userDAO.findById(uel.getUid());
			if(user!=null){
				UserEmail userEmail = null;
				String hql = "SELECT ue FROM UserEmail ue WHERE ue.uid="+user.getId()+" AND ue.email='"+uel.getObj()+"'";
				List<UserEmail> list = userEmailDAO.findByQuery(hql);
				userEmail = list!=null&&list.size()>0 ? list.get(0) : null;
				if(userEmail!=null){
					userEmail.setBindable(1);
					userEmail.setStatus(1);
					userEmailDAO.attachDirty(userEmail);
				}else{
					userEmail = new UserEmail(user.getId(),uel.getObj(),1,1,"");
					userEmailDAO.save(userEmail);
				}
				userEmailEventDAO.delete(uel);
				result="验证成功";
			}else{
				result="验证失败";
			}
		}
		return result;
	}
	private void sendBindEmail(User user,UserEmail ue){
		Date date = new Date();
		UserEmailEvent uel = new UserEmailEvent(user.getId(),ue.getEmail(),"",2,date.getTime());
		if(userEmailEventDAO.save(uel)>0){
			String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"controlAjax!activite.action?status="+uel.getCode();
			String title="邮箱绑定验证邮件";
			Map<String, Object> root = new HashMap<String, Object>();
			root.put("name", user.getName());
			root.put("email", ue.getEmail());
			root.put("href", href);
			String mailcontent = com.clip.util.FtlUtils.stringRender(root,"bindEmailVerify.ftl");
			SimpleMailSender.send(mailcontent,user.getName()+"，你有一个来自档期的消息", ue.getEmail());
		}
	}
	/**
	 * 绑定邮箱
	 * @param user	登录用户
	 * @param userEmail 绑定Email
	 * @param send	是否发送邮件(如果userEmail.getBindable()=0 那么send=true)
	 * @return
	 */
	public String bindUserEmail(User user,UserEmail userEmail,Boolean send){
		String result="{result:'该邮箱已被绑定'}";
		if(this.getUserEmailByEmail(userEmail.getEmail())==null){
			UserEmail ue=addUserEmail(userEmail);
			if(ue!=null){
				if(send)
					sendBindEmail(user,ue);
				result="{result:'添加成功,请登录邮箱验证您的Email.'}";
			}else{
				result="{result:'添加失败.'}";
			}
		}
		return result;
	}
	public String saveUserEmail(UserEmail userEmail,String descInput,Integer status){
		String result="";
		String hql="FROM UserEmail ue where ue.uid="+userEmail.getUid()+" and ue.bindable=1 and ue.status=1";
		List<UserEmail> ueList = userEmailDAO.findByQuery(hql);
		
		if(ueList!=null&&ueList.size()>0){
			if(status.equals(1)){
				userEmail.setStatus(status);
				result="{result:'修改成功',flag:1}";
			}else{
				if(ueList.size()>1){
					userEmail.setStatus(status);
					result="{result:'修改成功',flag:1}";
				}else{
					result="{result:'至少设置一个邮箱为接受邮箱',flag:0}";
				}
			}
		}
		userEmail.setDescription(ToolsUtils.htmlEnCode(descInput));
		userEmailDAO.getSession().clear();
		userEmailDAO.attachDirty(userEmail);
		return result;
		
	}
	public String resendEmail(User user,String email,String description){
		String result="{result:'邮件发送失败',flag:0}";
		String hql = "SELECT ue FROM UserEmail ue WHERE ue.uid="+user.getId()+" AND ue.email='"+email+"' AND ue.bindable=0";
		List<UserEmail> ueList = this.userEmailDAO.findByQuery(hql);
		UserEmail ue = null;
		ue = ueList!=null&&ueList.size()>0 ? ueList.get(0) : null;
		if(ue!=null){
			sendBindEmail(user,ue);
			result="{result:'邮件已发送.',flag:1}";
		}
		return result;
	}
	public Map<String,Object> getUserEmail(Integer uid){
		Map<String,Object> emailMap = new LinkedHashMap<String, Object>();
		List<UserEmail> userEmailList = userEmailDAO.findByUid(uid);
		for(UserEmail userEmail : userEmailList){
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("Id", userEmail.getId());
			map.put("Uid", userEmail.getUid());
			map.put("Email", userEmail.getEmail());
			map.put("Status", userEmail.getStatus());
			map.put("Bindable", userEmail.getBindable());
			map.put("Description", userEmail.getDescription());
			map.put("Dontacttypeid", userEmail.getContacttypeid());
			emailMap.put("email Eid="+userEmail.getId(), map);
		}
		return emailMap;
	}
}
